﻿using Dapper;
using Domain.Singleton_Pattern;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.MySQL_Infrastructure
{
    /// <summary>
    /// 数据库操作类
    /// </summary>
    public class SqlDapperHelper
    {
        static Singleton singleton = Singleton._instance;

        static int commandTimeout = 300;

        public static IDbConnection GetConnection()
        {
            return new MySqlConnection(singleton.ConnectionString);
        }

        /// <summary>
        ///  执行sql返回一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="useWriteConn"></param>
        /// <returns></returns>
        public static T ExecuteReaderReturnT<T>(string sql, object param = null, IDbTransaction transaction = null)
        {

            if (transaction == null)
            {
                using (IDbConnection conn = GetConnection())
                {
                    try
                    {
                        conn.Open();
                        return conn.QueryFirstOrDefault<T>(sql, param, commandTimeout: commandTimeout);
                    }
                    finally
                    {
                        conn.Open();
                    }
                }
            }
            else
            {
                var conn = transaction.Connection;
                return conn.QueryFirstOrDefault<T>(sql, param, commandTimeout: commandTimeout, transaction: transaction);
            }
        }
    }
}
